
package com.ceba.test.modules.email.service;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.AuthenticationFailedException;
import javax.mail.internet.MimeUtility;

import com.ceba.base.helper.LoggerHelper;
import com.ceba.cebautils.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.configs.CebaPathUtil;
import com.ceba.test.base.enums.EmailTypeEnum;
import com.ceba.test.base.enums.FileTypeEnum;
import com.ceba.test.base.enums.PeopleTypeEnum;
import com.ceba.base.web.service.IBaseService;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.modules.email.dao.MsgMailDao;
import com.ceba.test.modules.email.entity.EmailEntity;
import com.ceba.test.modules.email.entity.EmailEntitySubject;
import com.ceba.test.modules.email.entity.EmailRelationFile;
import com.ceba.test.modules.email.entity.EmailRelationPeople;
import com.ceba.test.modules.email.entity.EmailSubject;
import com.ceba.test.modules.email.entity.MsgEmailSet;
import com.ceba.test.modules.email.entity.MsgMail;
import com.ceba.test.modules.email.entity.UserInfoSet;

import abc.data.DataRow;
import abc.data.DataTable;
import abc.data.store.IStore;
import abc.data.store.StoreManager;
import abc.net.mail.client.MailClient;
import abc.object.IObject;
import abc.object.XObject;
import abc.user.IUser;
import abc.util.FileHelper;
import abc.util.StringUtils;


@SuppressWarnings("deprecation")
public class MsgMailService extends IBaseService {

	private static Logger logger = LoggerFactory.getLogger(MsgMailService.class);
	private MsgMailDao msgMailDao ;
	/**
	 * 取得发送邮件
	 * @param msgMail 
	 * @param mailTo 收件人 多个可以用 ；隔开
	 * @param title 邮件主题
	 * @param mailBody 邮件内容
	 * @param fileMap	附件  key：附件路径  value:附件名称
	 * @param htmlPath  html内嵌文件 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public EmailSubject getMailClient(MsgMail msgMail,String mailTo,String title,
			String mailBody,Map<String, String> fileMap,String[] htmlPath) throws UnsupportedEncodingException{
		/*MailClient mail = new MailClient();
		mail.setHost(msgMail.getSmtp()); // 邮件服务器地址
		mail.setUser(msgMail.getMail()); // 用户名
		mail.setPassword(msgMail.getPassword()); // 密码
		String name = msgMail.getName();
		String nick="";
		if(!StringUtil.isEmptyString(name)){
			nick = MimeUtility.encodeText(name);
			mail.setFrom(nick+" <"+msgMail.getMail()+">"); // 发件人邮箱
		}else{
			mail.setFrom(msgMail.getMail()); // 发件人邮箱
		}			
		mail.addTo(mailTo); // 收件人邮箱
		mail.setSubject(title); // 邮件主题
		
		mail.setContent(mailBody); // 邮件正文
		
*/		
		
		String subject=title;
    	String content=mailBody;
    	EmailTypeEnum emailTypeEnum=EmailTypeEnum.IMAGE_HTML_EMAIL;
    	List<EmailRelationPeople> peopleList=new ArrayList<>();
    	EmailRelationPeople people=new EmailRelationPeople(msgMail.getMail(),MimeUtility.encodeText(msgMail.getName()),PeopleTypeEnum.RECIPIENTS);
    	peopleList.add(people);
    	if(mailTo.indexOf(";")!=-1){
    		String[] emails=mailTo.split(";");
    		for(int i=0;i<emails.length;i++){
    			if(StringUtils.isNotEmpty(emails[i])){
    				EmailRelationPeople peopleTest=new EmailRelationPeople(emails[i],null,PeopleTypeEnum.ADDTO);
    		    	peopleList.add(peopleTest);
    			}
    		}
    	}else{
    		EmailRelationPeople peopleTest=new EmailRelationPeople(mailTo,null,PeopleTypeEnum.ADDTO);
	    	peopleList.add(peopleTest);
    	}
    	
    	List<EmailRelationFile> fileList=new ArrayList<>();
    	//附件
    	if(fileMap!=null && fileMap.size() != 0){
    		for(String key:fileMap.keySet()){
    			if(StringUtils.isNotEmpty(key)){
    				EmailRelationFile file=new EmailRelationFile(fileMap.get(key),key,FileTypeEnum.ATTACHMENT);
    				fileList.add(file);
    			}
    		}
    	}
    	//邮件内容关联文件
    	if(htmlPath!=null && htmlPath.length != 0){
    		for(int i=0;i<htmlPath.length;i++){
    			if(StringUtils.isNotEmpty(htmlPath[i])){
    				EmailRelationFile file=new EmailRelationFile(null,htmlPath[i],FileTypeEnum.HTML);
    				fileList.add(file);
    			}
    		}
    	}
    	
    	EmailEntity emailEntity=new EmailEntity(msgMail.getSmtp(), msgMail.getMail(), msgMail.getPassword(), content, subject, emailTypeEnum, peopleList);
    	emailEntity.setFileList(fileList);
		EmailSubject email=new EmailEntitySubject(emailEntity);
		return email;
	}
	
	public Boolean sendEmail(String title,String mailBody,String path,
			String mailTo,String reportName,String loginUserId)  {
		try {
			MsgMail msgMail=msgMailDao.getUserMailInfo(loginUserId);
			
			if(msgMail!=null && !StringUtil.isEmptyString(msgMail.getId())){
				Map<String, String> fileMap=new HashMap<>();
				if(!path.equals("")){
					if (!StringUtils.isNotNullAndEmpty(reportName)) {
						reportName="report";
					}
					fileMap.put(path,reportName+".pdf"); // 添加附件
				}
				EmailSubject mail = getMailClient(msgMail, mailTo, title, mailBody,fileMap,null);
				mail.send();
				return true;	
			}
		} catch ( AuthenticationFailedException e) {
			LoggerHelper.error(logger, e, "");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
			return false;
		}
		
		return false;
		
	}
	
	
	public MsgMail sendEmails(String loginUserId)  throws Exception   {
			MsgMail msgMail=msgMailDao.getUserMailInfo(loginUserId);
	    	return msgMail;
	}
	
	public Boolean sendEmailWidthOrig(String title,String mailBody,String path,
			String mailTo,String reportName,String origReport,String origRpath,String loginUserId) {
		try {
			MsgMail msgMail =msgMailDao.getUserMailInfo(loginUserId);
			
			if(msgMail!=null && !StringUtil.isEmptyString(msgMail.getId())){
				
				Map<String, String> fileMap=new HashMap<>();
				if(!path.equals("")){
					if (!StringUtils.isNotNullAndEmpty(reportName)) {
						reportName="report";
					}
					fileMap.put(path,reportName+".pdf"); // 添加附件
					fileMap.put(origRpath,origReport); // 添加附件
				}
				EmailSubject mail = getMailClient(msgMail, mailTo, title, mailBody,fileMap,null);
				mail.send();
				return true;	
			}
		} catch ( AuthenticationFailedException e) {
			LoggerHelper.error(logger, e, "");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		
		return false;
		
	}
	
	/**
	 * 测试邮箱是否能发送邮件
	 * @return
	 */
	public Boolean sendTestEmail(String sendMail,String STMP,String password)
			throws AuthenticationFailedException {
		String title=ResourceUtils.getMessage("MODULSE_SENDING_TEST_MAIL");
		String mailBody=ResourceUtils.getMessage("SENT_CEBA_CONFIGURING_SMTP");
		try {
			MailClient mail = new MailClient();
			mail.setHost(STMP); // 邮件服务器地址
			mail.setUser(sendMail); // 用户名
			mail.setPassword(password); // 密码
			mail.setFrom(" <"+sendMail+">"); // 发件人邮箱
			mail.addTo("services@quceba.com"); // 收件人邮箱
			mail.setSubject(title); // 邮件主题			
			mail.setContent(mailBody); // 邮件正文
			return mail.send();	
		}  catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return false;
	}
	
	
	/**
	 * 保存用户邮件发送信息
	 * @param mail 邮箱
	 * @param name 名字
	 * @param smtp 
	 * @param password
	 * @return
	 */
	public Boolean saveUserMailInfo(String mail,String name,
			String smtp,String password,String content,String loginUserId)throws Exception{
				
		IStore store = StoreManager.create("msg_mail");
		IObject object = new XObject("msg_mail");
		object.put("ID",loginUserId);
		object.put("USER_ID",loginUserId);
		object.put("MAIL",mail);
		object.put("NAME",name);
		object.put("SMTP",smtp);
		object.put("PASSWORD",CebaConfig.getEncode(password));
		object.put("content", content);
		if(store.save(object)>0){
			return true;
		}
		return false;
		
	}
	
	public boolean deleteMailInfo(String name,String userId)throws Exception{
		return msgMailDao.deleteMailInfo(name,userId);
	}
	
	public IObject getUserMailInfo(String loginUserId) throws Exception{		
		IStore store = StoreManager.create("msg_mail");
		IObject object = null;
		if(null != loginUserId){
			object = store.get(loginUserId);
		}
		if(object==null){
			 object = store.get("1");
		}
		else{
			if(object.getString("MAIL").equals("") || object.getString("SMTP").equals("") || object.getString("PASSWORD").equals("")){
				 object = store.get("1");
			}
		}
		
		return object;
		
	}

	/**
	 * 发送报告附件
	 * @param loginUserId
	 * @return
	 */
	public MsgMail sendEmailAttach(String loginUserId) {
		MsgMail msgMail=null;
		try {
			 msgMail =msgMailDao.getUserMailInfo(loginUserId);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return msgMail;
		
	}
	
	/**
	 * 添加一个常用的EMAIL
	 * @param mail email
	 * @return
	 */
	public Boolean addSendEMail(String mail,String loginUserId)throws Exception{
		return msgMailDao.addSendEMail(mail,loginUserId);
	}

	/**
	 * 给企业发送激活码邮件
	 * @param title
	 * @param mailBody
	 * @param mailTo
	 * @return
	 */
	public Boolean sendEnterpriseActivateCodeEmail(String title,String mailBody,
												   String mailTo) {
		try {
			MsgMail msgMail=msgMailDao.getUserMailInfo(null);
			if(msgMail !=null && !StringUtil.isEmptyString(msgMail.getId())){
				MailClient mail = getOldMailClient(msgMail, mailTo, title, mailBody);
				return mail.send();

			}
		} catch ( AuthenticationFailedException e) {
			LoggerHelper.error(logger, e, "");
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}

		return false;

	}
	public String parseEmailHtml(MsgEmailSet msgMailSet, String title, String txt,String mailContent) {
		String html="<!DOCTYPE html><html><hea><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><title>#TITLE#</title></head><body style='font-family: Microsoft YaHei, Arial, Helvetica, sans-serif;font-size: 14px;'><div style='margin-left:10px;'><div style='line-height:18px;padding-bottom:10px;padding-left:20px;'><p style='text-indent:28px;'>#CONTEXT#</p>#mailContent#</div></div></body></html>";
		if(title.equals("")){
			title=msgMailSet.getTitle();
		}
		html=html.replace("#TITLE#", title).replace("#CONTEXT#", txt).replace("#mailContent#", mailContent);
		return html;
	}

	/**
	 * 保存邮件配置
	 * @param string
	 * @param mail
	 * @param name
	 * @param smtp
	 * @param pw
	 * @return
	 */
	public boolean addMsgEmail(String string, String mail, String name, String smtp, String pw) {
		IStore store = StoreManager.create("msg_mail");
		XObject object = new XObject("ID","1");
		object.put("MAIL", mail);
		object.put("NAME", name);
		object.put("SMTP", smtp);
		object.put("PASSWORD", CebaConfig.getEncode(pw));
		if(store.save(object)<0){
			return true;
		}
		return false;
	}
	
	
	/**
	 * 获取msg_mail的单个信息
	 * 
	 */
	public MsgMail getMsgMailById(String id) throws Exception{
		return  msgMailDao.getMsgMailById(id);
	}

	
	/**
	 * 发送邮件：
	 * 邮件内容为HTML
	 * html内嵌文件 例如 <img src="" />
	 * @param title
	 * @param mailBody
	 * @param path
	 * @param mailTo
	 * @param reportName
	 * @param htmlPath
	 * @return
	 * @throws Exception
	 */
	public boolean sendEmailHtmlFile(String title, String mailBody, String[] path, String mailTo, String[] reportName,
			String[] htmlPath,String loginUserId)throws Exception {
		MsgMail msgMail=msgMailDao.getUserMailInfo(loginUserId);
		String subject=title;
    	String content=mailBody;
    	EmailTypeEnum emailTypeEnum=EmailTypeEnum.IMAGE_HTML_EMAIL;
    	List<EmailRelationPeople> peopleList=new ArrayList<>();
    	
    	EmailRelationPeople people=new EmailRelationPeople(msgMail.getMail(),MimeUtility.encodeText(msgMail.getName()),PeopleTypeEnum.RECIPIENTS);
    	peopleList.add(people);
    	if(mailTo.indexOf(";")!=-1){
    		String[] emails=mailTo.split(";");
    		for(int i=0;i<emails.length;i++){
    			if(StringUtils.isNotEmpty(emails[i])){
    				EmailRelationPeople peopleTest=new EmailRelationPeople(emails[i],null,PeopleTypeEnum.ADDTO);
    		    	peopleList.add(peopleTest);
    			}
    		}
    	}else{
    		EmailRelationPeople peopleTest=new EmailRelationPeople(mailTo,null,PeopleTypeEnum.ADDTO);
	    	peopleList.add(peopleTest);
    	}
    	
    	List<EmailRelationFile> fileList=new ArrayList<>();
    	//附件
    	if(path!=null && path.length != 0){
    		for(int i=0;i<path.length;i++){
    			if(StringUtils.isNotEmpty(path[i])){
    				EmailRelationFile file=new EmailRelationFile(reportName[i],path[i],FileTypeEnum.ATTACHMENT);
    				fileList.add(file);
    			}
    		}
    	}
    	//邮件内容关联文件
    	if(htmlPath!=null && htmlPath.length != 0){
    		for(int i=0;i<htmlPath.length;i++){
    			if(StringUtils.isNotEmpty(htmlPath[i])){
    				EmailRelationFile file=new EmailRelationFile(null,htmlPath[i],FileTypeEnum.HTML);
    				fileList.add(file);
    			}
    		}
    	}
    	
    	EmailEntity emailEntity=new EmailEntity(msgMail.getSmtp(), msgMail.getMail(), msgMail.getPassword(), content, subject, emailTypeEnum, peopleList);
    	emailEntity.setFileList(fileList);
		EmailSubject email=new EmailEntitySubject(emailEntity);
		email.send();
		return true;
	}

	
	
	public List<String> htmlFilePath(String str) { 
		List<String> resultList=new ArrayList<>();
		String regx="(?<=(src=\"))[.\\s\\S]*?(?=(\"))";
	    //1.将正在表达式封装成对象Patten 类来实现 
	    Pattern pattern = Pattern.compile(regx); 
	    //2.将字符串和正则表达式相关联 
	    Matcher matcher = pattern.matcher(str); 
	    //3.String 对象中的matches 方法就是通过这个Matcher和pattern来实现的。 
	    System.out.println(matcher.matches()); 
	    //查找符合规则的子串 
	    while(matcher.find()){ 
	    	resultList.add(matcher.group());
	    } 
	    return resultList;
  } 
	
	public MsgMail getMsgMailByUserId(String loginUserId) throws Exception{
		DataTable dt = msgMailDao.getMsgMailByUserId(loginUserId);
		MsgMail msgMail = new MsgMail();
		if(dt !=null && dt.getRowCount()>0){
			DataRow dr = dt.getRow(0);
			msgMail.setId(dr.getString("ID"));
			msgMail.setUserId(dr.getString("USER_ID"));
			msgMail.setMail(dr.getString("MAIL"));
			msgMail.setSmtp(dr.getString("SMTP"));
			msgMail.setPassword(dr.getString("PASSWORD"));
			msgMail.setContent(dr.getString("CONTENT"));
		}
		return msgMail;
		
	}
	
	
	/**
	 * 根据ID取得邮件设置数据
	 * @param id
	 * @return
	 */
	public  MsgMail getMsgEmailByUserId(String id){
		MsgMail msgMail = new MsgMail();
		msgMail.setId(id);
		try {
			DataTable dt = msgMailDao.getMsgMailByUserId(id);
			if(dt !=null && dt.getRowCount()>0){
				DataRow dr = dt.getRow(0);
				msgMail.setId(dr.getString("ID"));
				msgMail.setUserId(dr.getString("USER_ID"));
				msgMail.setMail(dr.getString("MAIL"));
				msgMail.setSmtp(dr.getString("SMTP"));
				msgMail.setPassword(CebaConfig.getDecode(dr.getString("PASSWORD")));
				msgMail.setContent(dr.getString("CONTENT"));
				msgMail.setName(dr.getString("NAME"));
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return msgMail;
	}
	
	public UserInfoSet getUserInfoSet(IUser user){
 		return msgMailDao.getUserInfoSet(user);
 }
	
	public boolean getMsgMailAddContent(String content){
		return msgMailDao.getMsgMailAddContent(content);
	}
	
	
	public MsgMailDao getMsgMailDao() {
		return msgMailDao;
	}

	public void setMsgMailDao(MsgMailDao msgMailDao) {
		this.msgMailDao = msgMailDao;
	}


	public List<MsgMail> getAllMsgMail() {
		return msgMailDao.getAllMsgMail();
	}

	public boolean updateContent(String id, String value) {
		return msgMailDao.updateContent(id,value);
	}

	/**
	 * 取得发送邮件
	 * @param msgMail
	 * @param mailTo 收件人 多个可以用 ；隔开
	 * @param title 邮件主题
	 * @param mailBody 邮件内容
	 * @return
	 * @throws Exception
	 */
	private MailClient getOldMailClient(MsgMail msgMail, String mailTo, String title,
										String mailBody) throws Exception{
		MailClient mail = new MailClient();
		mail.setHost(msgMail.getSmtp()); // 邮件服务器地址
		mail.setUser(msgMail.getMail()); // 用户名
		mail.setPassword(msgMail.getPassword()); // 密码
		String name = msgMail.getName();
		String nick="";
		if(!StringUtil.isEmptyString(name)){
			nick = MimeUtility.encodeText(name);
			mail.setFrom(nick+" <"+msgMail.getMail()+">"); // 发件人邮箱
		}else{
			mail.setFrom(msgMail.getMail()); // 发件人邮箱
		}
		mail.addTo(mailTo); // 收件人邮箱
		mail.setSubject(title); // 邮件主题

		mail.setContent(mailBody); // 邮件正文

		return mail;
	}
}
